from django.db import models
import django.contrib.auth as auth
import students.models as students
from django.db.models import UniqueConstraint

# Create your models here.
class Survey(models.Model):
    survey_id = models.CharField(max_length=120, unique=True, primary_key=True)
    survey_name = models.CharField(max_length=512, unique=True)
    # {回收/暂停/删除/未发布}
    survey_status = models.CharField(max_length=512, default="未发布")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    # 用户只能inactive，不能删除
    create_user = models.ForeignKey('auth.User',
                                    related_name='create',
                                    on_delete=models.PROTECT)
    update_user = models.ForeignKey('auth.User',
                                    related_name='update',
                                    on_delete=models.PROTECT)
    
    def __str__(self):
        return self.survey_name

    class Meta:
        verbose_name = "调查问卷"
        verbose_name_plural = "调查问卷"

class Question(models.Model):
    QTYPES = (
        ('radio', '单选'),
        ('checkbox', '多选'),
        ('text', '填空'),
    )

    qid = models.CharField(max_length=120, primary_key=True)
    qtext = models.CharField(max_length=512)
    qtype = models.CharField(choices=QTYPES, max_length=20, default='radio')
    qnum = models.IntegerField()
    required = models.BooleanField(default=False)
    fill_others = models.BooleanField(default=False)
    options = models.JSONField()

    survey = models.ForeignKey('Survey', on_delete=models.CASCADE)

    def __str__(self):
        return f'[{self.qid}]_[{self.qtype}]_{self.qtext}'

    class Meta:
        verbose_name = "问题"
        verbose_name_plural = "问题"

# 记录操作时长等详细信息
class AnswerSet(models.Model):
    survey = models.ForeignKey('Survey',
                                on_delete=models.PROTECT)
    student = models.ForeignKey('students.Student',
                                on_delete=models.PROTECT)
    answer =  models.JSONField()

    start_time = models.DateTimeField(null=True)
    end_time = models.DateTimeField(null=True)

    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'[{self.survey.survey_name}]_[{self.student.student_name}]'

    class Meta:
        verbose_name = "问卷回答"
        verbose_name_plural = "问卷回答"
        constraints = [
            UniqueConstraint(name="survey_student",
                            fields=['survey', 'student'])
        ]